package com.storage;

import com.storage.service.MySequenceService;
import com.storage.service.impl.MySequenceServiceImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SpringBootApplication
public class StorageApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(StorageApplication.class, args);
        testYali(run.getBean(MySequenceService.class));
    }

    private static void testYali(MySequenceService mySequenceService) {
        long start = System.currentTimeMillis();

        int threadCount = 10;      // 线程数
        int idsPerThread = 1000;   // 每个线程生成 ID 数量
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        // 用线程安全的 Set 保存所有生成的 ID
        Set<String> allIds = Collections.synchronizedSet(new HashSet<>());

        for (int i = 0; i < threadCount; i++) {
            executor.submit(() -> {
                for (int j = 0; j < idsPerThread; j++) {
                    String id = mySequenceService.getSequence();

                    // 检查唯一性
                    if (!allIds.add(id)) {
                        System.err.println("重复ID发现: " + id);
                    }

                    try {
                        Thread.sleep(1); // 模拟业务处理
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            });
        }

        executor.shutdown();
        try {
            while (!executor.isTerminated()) {
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println("生成完成，总ID数: " + allIds.size());
        System.out.println("耗时：" + (end - start));
    }
}
